<extend name="Public/base" />
<block name="content">
<link rel="stylesheet" type="text/css" href="__STATIC__/webuploader/css/webuploader.css" />
<link rel="stylesheet" type="text/css" href="__STATIC__/webuploader/css/style.css" />
<style>
div.uploader{
	display:none;
}
</style>
<div id="content">
	<div id="content-header">
		<div id="breadcrumb">
			<a class="tip-bottom" href="{:U('Index/index')}" data-original-title="首页"><i class="icon-home"></i> 首页</a>
			<a class="tip-bottom" href="{:U('Shop/index')}" data-original-title="">{$meta_title_c}</a> 
			<a class="current" href="{$post_url}">{$meta_title}</a>
		</div>
	</div>
	<div class="container-fluid">
		<br/>
		<div class="row-fluid">
			<div class="span12">
				<div class="widget-box">
					<div class="widget-title">
						<span class="icon"> <i class="icon-align-justify"></i></span>
						<h5>{$meta_title}</h5>
					</div>
					<div class="widget-content nopadding">
						<form class="form-horizontal" method="post" action="">
							<div class="control-group">
								<label class="control-label"><font color="red">*</font>所属商户:</label>
								<div class="controls">
									<select class="form-control span3" name="merchant_id">
										<option value="0">请选择商户</option>
										<volist name="merchant_list" id="vo">
											<option value="{$vo.merchant_id}">{$vo.merchant_name|strip_tags}</option>
										</volist>
									</select>
								</div>
							</div>
							<div class="control-group">
								<label class="control-label"><font color="red">*</font>线下品类:</label>
								<div class="controls">
									<select class="form-control span3" name="conf_category_id">
										<option value="0">请选择品类</option>
										<volist name="conf_category_list" id="vo">
											<option value="{$vo.conf_category_id}">{$vo.conf_category|strip_tags}</option>
										</volist>
									</select>
								</div>
							</div>
							
							<div class="control-group">
								<label class="control-label"><font color="red">*</font>店铺名称:</label>
								<div class="controls">
									<input type="text" placeholder="店铺名称1-15个字符" maxlength="15" class="ui-wizard-content span3" name="shop_name" value="{$list.shop_name|htmlspecialchars}" >
								</div>
							</div>
							<div class="control-group">
								<label class="control-label"><font color="red">*</font>店铺介绍:</label>
								<div class="controls">
									<textarea class="span7" maxlength="150" placeholder="店铺介绍1-150个字符" name="shop_introduction">{$list.shop_introduction}</textarea>
								</div>
							</div>
							<div class="control-group">
								<label class="control-label"><font color="red">*</font>店铺地址:</label>
								<div class="controls">
									<input type="text" placeholder="店铺名称1-25个字符" maxlength="25" class="ui-wizard-content span7" name="shop_address" value="{$list.shop_address|htmlspecialchars}" >
								</div>
							</div>
							<div class="control-group">
								<label class="control-label"><font color="red">*</font>店铺排序:</label>
								<div class="controls">
									<input type="text" maxlength="15" class="ui-wizard-content span3" name="sort" value="<gt name='list.sort' value='0'>{$list.sort|htmlspecialchars}<else/>0</gt>" >
								</div>
							</div>
							<div class="control-group">
								<label class="control-label">店铺品类:</label>
								<div class="controls">
									<select class="form-control span3" name="shop_category_id">
										<option value="0">请选择店铺品类</option>
											<volist name="shopCategoryList" id="vo">
												<option value="{$vo.shop_category_id}">{$vo.shop_category_name|strip_tags}</option>
											</volist>
										</notempty>
									</select>
								</div>
							</div>
							<div class="control-group" style="line-height:46px;">
								<label class="control-label">商品品类:</label>
								<div style="width:950px;float:left;">
									<volist name='first_category' id='vo'>
										<label class="checkbox">
											<if condition="$vo.checked eq 1">
												<input type="checkbox" checked="true" value="{$vo.goods_category_id}" name="goods_category_id[]">{$vo.goods_category_name}
											<else />
												<input type="checkbox" value="{$vo.goods_category_id}" name="goods_category_id[]">{$vo.goods_category_name}
											</if>
										</label>
									</volist>
								</div>
							</div>
							
							<input type="hidden" name="logo_id" id="logo_id" value="{$list.logo_id}">
							<notempty name="list.logo_id">
                                <div class="control-group">
                                    <label class="control-label">店铺封面图:</label>
                                    <div class="controls">
                                        <img src="{$list.logo_id|getPictureThumb=###,300,300}" />
                                    </div>
                                </div>
                            </notempty>
                            <div class="control-group">
								<label class="control-label">店铺logo:</label>
								<div class="controls">
									<div id="wrapper">
								        <div id="container">
								            <!--头部，相册选择和格式选择-->
								            <div id="uploader" class="uploader_logo">
								                <div class="queueList">
								                    <div id="dndArea" class="dndArea_logo placeholder">
								                        <div id="filePicker" class="filePicker_logo"></div>
								                        <p>或将照片拖到这里，单次最多可选1张</p>
								                    </div>
								                </div>
								                <div class="statusBar" style="display:none;">
								                    <div class="progress">
								                        <span class="text">0%</span>
								                        <span class="percentage"></span>
								                    </div><div class="info"></div>
								                    <div class="btns">
								                        <div id="filePicker2" class="filePicker2.logo"></div><div class="uploadBtn">开始上传</div>
								                    </div>
								                </div>
								            </div>
								        </div>
								    </div>
								</div>
							</div>
							
							<input type="hidden" name="cover_id" id="cover_id" value="{$list.cover_id}">
							<notempty name="list.cover_id">
                                <div class="control-group">
                                    <label class="control-label">店铺封面图:</label>
                                    <div class="controls">
                                        <img src="{$list.cover_id|getPictureThumb=###,300,300}" />
                                    </div>
                                </div>
                            </notempty>
                            <div class="control-group">
								<label class="control-label">店铺封面图:</label>
								<div class="controls">
									<div id="wrapper">
								        <div id="container">
								            <!--头部，相册选择和格式选择-->
								            <div id="uploader" class="uploader_cover">
								                <div class="queueList">
								                    <div id="dndArea" class="dndArea_cover placeholder">
								                        <div id="filePicker" class="filePicker_cover"></div>
								                        <p>或将照片拖到这里，单次最多可选1张</p>
								                    </div>
								                </div>
								                <div class="statusBar" style="display:none;">
								                    <div class="progress">
								                        <span class="text">0%</span>
								                        <span class="percentage"></span>
								                    </div><div class="info"></div>
								                    <div class="btns">
								                        <div id="filePicker2" class="filePicker2_cover"></div><div class="uploadBtn">开始上传</div>
								                    </div>
								                </div>
								            </div>
								        </div>
								    </div>
								</div>
							</div>

							<div class="form-actions">
								<button class="btn btn-success" type="submit">提交</button>
							</div>
							<input type="hidden" name="shop_id" value="{$list.shop_id}"/>
						</form>
					</div>
				</div>
			</div>
		</div>
	</div>
</div>
<script type="text/javascript">
$(document).ready(function(){
	
	//设置下拉框选中
	set_value("merchant_id", "{$list.merchant_id|default=0}");
	set_value("conf_category_id", "{$list.conf_category_id|default=0}");
	set_value("shop_category_id", "{$list.shop_category_id|default=0}");
	//初始化登录用户名输入焦点
	tke_form_focus();
	$("form").submit(function(){
		var shop_id = $.trim($('input[name=shop_id]').val());
		//锁定登录按钮
		$('button').attr('disabled',true);
		var self = $(this);
		$.post("{$post_url}", self.serialize(), call_back, "json");
		return false;
		
		/**
		 * @todo 接收登录返回值
		 * @author PHP@妖孽 <dino_ma@163.com>
		 */
		function call_back(data){
			if(data.status==1){
				tke_alert(data.info,'alert-success');
				setTimeout(function(){
					if(shop_id == '' || shop_id == undefined){
						var r = confirm("操作成功,跳转到时店铺绑定页")
						if( r == true){
							location.href="{:U('Shop/addActivity')}";
						}else{
							location.href="{:U('Shop/index')}";
						}
					}else{
						location.href="{:U('Shop/index')}";
					}
				},1500);
			} else {
				$('button').attr('disabled',false);
				tke_alert(data.info,'alert-error');
			}
		}
	});
	//导航高亮
	highlight_subnav("{:U('Shop/index')}");
});

</script>

<script type="text/javascript" src="__STATIC__/webuploader/js/webuploader.nolog.js"></script>
<script type="text/javascript">
(function( $ ){
	
    	function upload(wrap,filePicker,filePicker2,dndArea,input){  
			var upload = new Object;  
			upload.filePicker = filePicker;
			upload.filePicker2 = filePicker2;
			upload.dnd = dndArea;
			upload.paste = wrap;
			upload.wrap = $(wrap);
			upload.input_id = input;
	        upload.queue = $( '<ul class="filelist"></ul>' ).appendTo( upload.wrap.find( '.queueList' ) );// 图片容器
	        upload.statusBar = upload.wrap.find( '.statusBar' );// 状态栏，包括进度和控制按钮
	        upload.info = upload.statusBar.find( '.info' );// 文件总体选择信息。
	        upload.uploadBtn = upload.wrap.find( '.uploadBtn' );// 上传按钮
	        upload.placeHolder = upload.wrap.find( '.placeholder' );// 没选择文件之前的内容。
	        upload.progress = upload.statusBar.find( '.progress' ).hide();
	        upload.fileCount = 0;// 添加的文件数量
	        upload.fileSize = 0;// 添加的文件总大小
	        upload.ratio = window.devicePixelRatio || 1;// 优化retina, 在retina下这个值是2
	        upload.thumbnailWidth = 110 * upload.ratio;// 缩略图大小
	        upload.thumbnailHeight = 110 * upload.ratio;
	        upload.state = 'pedding'; // 可能有pedding, ready, uploading, confirm, done.
	        upload.percentages = {};// 所有文件的进度信息，key为file id
	        // 判断浏览器是否支持图片的base64
	        upload.isSupportBase64 = ( function() {
	            var data = new Image();
	            var support = true;
	            data.onload = data.onerror = function() {
	                if( this.width != 1 || this.height != 1 ) {
	                    support = false;
	                }
	            }
	            data.src = "";
	            return support;
	        } )();
	        // 检测是否已经安装flash，检测flash的版本
	        upload.flashVersion = ( function() {
	            var version;
	            try {
	                version = navigator.plugins[ 'Shockwave Flash' ];
	                version = version.description;
	            } catch ( ex ) {
	                try {
	                    version = new ActiveXObject('ShockwaveFlash.ShockwaveFlash')
	                            .GetVariable('$version');
	                } catch ( ex2 ) {
	                    version = '0.0';
	                }
	            }
	            version = version.match( /\d+/g );
	            return parseFloat( version[ 0 ] + '.' + version[ 1 ], 10 );
	        } )();

	        upload.supportTransition = (function(){
	            var s = document.createElement('p').style,
	                r = 'transition' in s ||
	                        'WebkitTransition' in s ||
	                        'MozTransition' in s ||
	                        'msTransition' in s ||
	                        'OTransition' in s;
	            s = null;
	            return r;
	        })();

	        // WebUploader实例
	        upload.uploader;
			
	        // 实例化
	        upload.uploader = WebUploader.create({
	            pick: {
	                id: upload.filePicker,
	                label: '点击选择图片'
	            },
	            formData: {
	            },
	            dnd: upload.dnd,
	            paste: upload.paste,
	            swf: "__STATIC__"+'/webuploader/js/Uploader.swf',
	            chunked: false,
	            chunkSize: 512 * 1024,
	            server: '{:U("File/uploadPicture")}',
	            // runtimeOrder: 'flash',
	
	            accept: {
	                 title: 'Images',
	                 extensions: 'jpg,jpeg,bmp,png',
	                 mimeTypes: 'image/*'
	             }, 
	
	            // 禁掉全局的拖拽功能。这样不会出现图片拖进页面的时候，把图片打开。
	            disableGlobalDnd: true,
	            fileNumLimit: 2,
	            fileSizeLimit: 1 * 1024 * 1024,    // 200 M
	            fileSingleSizeLimit: 1 * 1024 * 1024    // 50 M
	        });
    	   
	        upload.addFile = function( file ) {
	            var $li = $( '<li id="' + file.id + '">' +
	                    '<p class="title">' + file.name + '</p>' +
	                    '<p class="imgWrap"></p>'+
	                    '<p class="progress"><span></span></p>' +
	                    '</li>' ),

	                $btns = $('<div class="file-panel">' +
	                    '<span class="cancel">删除</span>' +
	                    '<span class="rotateRight">向右旋转</span>' +
	                    '<span class="rotateLeft">向左旋转</span></div>').appendTo( $li ),
	                $prgress = $li.find('p.progress span'),
	                $wrap = $li.find( 'p.imgWrap' ),
	                $info = $('<p class="error"></p>'),

	                showError = function( code ) {
	                    switch( code ) {
	                        case 'exceed_size':
	                            text = '文件大小超出';
	                            break;

	                        case 'interrupt':
	                            text = '上传暂停';
	                            break;

	                        default:
	                            text = '上传失败，请重试';
	                            break;
	                    }

	                    $info.text( text ).appendTo( $li );
	                };
	                
	            if ( file.getStatus() === 'invalid' ) {
	                showError( file.statusText );
	            } else {
	                // @todo lazyload
	                $wrap.text( '预览中' );
	                upload.uploader.makeThumb( file, function( error, src ) {
	                    var img;

	                    if ( error ) {
	                    	$wrap.text( '不能预览' );
	                        return;
	                    }

	                    if( upload.isSupportBase64 ) {
	                        img = $('<img src="'+src+'">');
	                        $wrap.empty().append( img );
	                    } else {
	                        $.ajax('../../server/preview.php', {
	                            method: 'POST',
	                            data: src,
	                            dataType:'json'
	                        }).done(function( response ) {
	                            if (response.result) {
	                                img = $('<img src="'+response.result+'">');
	                                $wrap.empty().append( img );
	                            } else {
	                            	$wrap.text("预览出错");
	                            }
	                        });
	                    }
	                }, upload.thumbnailWidth, upload.thumbnailHeight );

	                upload.percentages[ file.id ] = [ file.size, 0 ];
	                file.rotation = 0;
	            }

	            file.on('statuschange', function( cur, prev ) {
	                if ( prev === 'progress' ) {
	                    $prgress.hide().width(0);
	                } else if ( prev === 'queued' ) {
	                    $li.off( 'mouseenter mouseleave' );
	                    $btns.remove();
	                }

	                // 成功
	                if ( cur === 'error' || cur === 'invalid' ) {
	                    console.log( file.statusText );
	                    showError( file.statusText );
	                    upload.percentages[ file.id ][ 1 ] = 1;
	                } else if ( cur === 'interrupt' ) {
	                    showError( 'interrupt' );
	                } else if ( cur === 'queued' ) {
	                	upload.percentages[ file.id ][ 1 ] = 0;
	                } else if ( cur === 'progress' ) {
	                    $info.remove();
	                    $prgress.css('display', 'block');
	                } else if ( cur === 'complete' ) {
	                    $li.append( '<span class="success"></span>' );
	                }

	                $li.removeClass( 'state-' + prev ).addClass( 'state-' + cur );
	            });

	            $li.on( 'mouseenter', function() {
	                $btns.stop().animate({height: 30});
	            });

	            $li.on( 'mouseleave', function() {
	                $btns.stop().animate({height: 0});
	            });

	            $btns.on( 'click', 'span', function() {
	                var index = $(this).index(),
	                    deg;

	                switch ( index ) {
	                    case 0:
	                        uploader.removeFile( file );
	                        return;

	                    case 1:
	                        file.rotation += 90;
	                        break;

	                    case 2:
	                        file.rotation -= 90;
	                        break;
	                }

	                if ( upload.supportTransition ) {
	                    deg = 'rotate(' + file.rotation + 'deg)';
	                    $wrap.css({
	                        '-webkit-transform': deg,
	                        '-mos-transform': deg,
	                        '-o-transform': deg,
	                        'transform': deg
	                    });
	                } else {
	                    $wrap.css( 'filter', 'progid:DXImageTransform.Microsoft.BasicImage(rotation='+ (~~((file.rotation/90)%4 + 4)%4) +')');
	                    // use jquery animate to rotation
	                    // $({
	                    //     rotation: rotation
	                    // }).animate({
	                    //     rotation: file.rotation
	                    // }, {
	                    //     easing: 'linear',
	                    //     step: function( now ) {
	                    //         now = now * Math.PI / 180;

	                    //         var cos = Math.cos( now ),
	                    //             sin = Math.sin( now );

	                    //         $wrap.css( 'filter', "progid:DXImageTransform.Microsoft.Matrix(M11=" + cos + ",M12=" + (-sin) + ",M21=" + sin + ",M22=" + cos + ",SizingMethod='auto expand')");
	                    //     }
	                    // });
	                }


	            });

	            $li.appendTo( upload.queue );
	        }

	        // 负责view的销毁
	        upload.removeFile = function( file ) {
	            var $li = $('#'+file.id);

	            delete upload.percentages[ file.id ];
	            upload.updateTotalProgress();
	            $li.off().find('.file-panel').off().end().remove();
	        }

	        upload.updateTotalProgress = function() {
	            var loaded = 0,
	                total = 0,
	                spans = upload.progress.children(),
	                percent;

	            $.each( upload.percentages, function( k, v ) {
	                total += v[ 0 ];
	                loaded += v[ 0 ] * v[ 1 ];
	            } );

	            percent = total ? loaded / total : 0;


	            spans.eq( 0 ).text( Math.round( percent * 100 ) + '%' );
	            spans.eq( 1 ).css( 'width', Math.round( percent * 100 ) + '%' );
	            upload.updateStatus();
	        }

	        upload.updateStatus = function() {
	            var text = '', stats;

	            if ( upload.state === 'ready' ) {
	                text = '选中' + upload.fileCount + '张图片，共' +
	                        WebUploader.formatSize( upload.fileSize ) + '。';
	            } else if ( upload.state === 'confirm' ) {
	                stats = uploader.getStats();
	                if ( stats.uploadFailNum ) {
	                    text = '已成功上传' + stats.successNum+ '张照片至XX相册，'+
	                        stats.uploadFailNum + '张照片上传失败，<a class="retry" href="#">重新上传</a>失败图片或<a class="ignore" href="#">忽略</a>'
	                }

	            } else {
	                stats = upload.uploader.getStats();
	                text = '共' + upload.fileCount + '张（' +
	                        WebUploader.formatSize( upload.fileSize )  +
	                        '），已上传' + stats.successNum + '张';

	                if ( stats.uploadFailNum ) {
	                    text += '，失败' + stats.uploadFailNum + '张';
	                }
	            }

	            upload.info.html( text );
	        }

	        upload.setState = function( val ) {
	            var file, stats;

	            if ( val === upload.state ) {
	                return;
	            }

	            upload.uploadBtn.removeClass( 'state-' + upload.state );
	            upload.uploadBtn.addClass( 'state-' + val );
	            upload.state = val;

	            switch ( upload.state ) {
	                case 'pedding':
	                	upload.placeHolder.removeClass( 'element-invisible' );
	                    upload.queue.hide();
	                    upload.statusBar.addClass( 'element-invisible' );
	                    upload.uploader.refresh();
	                    break;

	                case 'ready':
	                	upload.placeHolder.addClass( 'element-invisible' );
	                    $( upload.filePicker2 ).removeClass( 'element-invisible');
	                    upload.queue.show();
	                    upload.statusBar.removeClass('element-invisible');
	                    upload.uploader.refresh();
	                    break;

	                case 'uploading':
	                    $( upload.filePicker2 ).addClass( 'element-invisible' );
	                    upload.progress.show();
	                    upload.uploadBtn.text( '暂停上传' );
	                    break;

	                case 'paused':
	                	upload.progress.show();
	                	upload.uploadBtn.text( '继续上传' );
	                    break;

	                case 'confirm':
	                	upload.progress.hide();
	                    $( upload.filePicker2  ).removeClass( 'element-invisible' );
	                    upload.uploadBtn.text( '开始上传' );

	                    stats = upload.uploader.getStats();
	                    if ( stats.successNum && !stats.uploadFailNum ) {
	                    	upload.setState( 'finish' );
	                        return;
	                    }
	                    break;
	                case 'finish':
	                    stats = upload.uploader.getStats();
	                    if ( stats.successNum ) {
	                    	tke_alert('上传成功','alert-success');
	                    } else {
	                        // 没有成功的图片，重设
	                        upload.state = 'done';
	                        location.reload();
	                    }
	                    break;
	            }

	            upload.updateStatus();
	        }
	        
	        // 拖拽时不接受 js, txt 文件。
	        upload.uploader.on( 'dndAccept', function( items ) {
	            var denied = false,
	                len = items.length,
	                i = 0,
	                // 修改js类型
	                unAllowed = 'text/plain;application/javascript ';

	            for ( ; i < len; i++ ) {
	                // 如果在列表里面
	                if ( ~unAllowed.indexOf( items[ i ].type ) ) {
	                    denied = true;
	                    break;
	                }
	            }

	            return !denied;
	        });
	        
	        upload.uploader.on('ready', function() {
	            window.uploader = upload.uploader;
	        });
			
	      	//上传成功回调函数
	        upload.uploader.on('uploadSuccess',function(file,respone){
	            $(upload.input_id).val(respone.data.id);
	        });
	      
	        uploader.onUploadProgress = function( file, percentage ) {
	        	alert(1)
	            var $li = $('#'+file.id),
	                $percent = $li.find('.progress span');

	            $percent.css( 'width', percentage * 100 + '%' );
	            upload.percentages[ file.id ][ 1 ] = percentage;
	            upload.updateTotalProgress();
	        };

	        upload.uploader.onFileQueued = function( file ) {
	        	upload.fileCount++;
	        	upload.fileSize += file.size;

	            if ( upload.fileCount === 1 ) {
	            	upload.placeHolder.addClass( 'element-invisible' );
	            	upload.statusBar.show();
	            }
	            
	            upload.addFile( file );
	            upload.setState( 'ready' );
	            upload.updateTotalProgress();
	        };

	        upload.uploader.onFileDequeued = function( file ) {
	            upload.fileCount--;
	            upload.fileSize -= file.size;

	            if ( !upload.fileCount ) {
	            	upload.setState( 'pedding' );
	            }

	            upload.removeFile( file );
	            upload.updateTotalProgress();

	        };

	        upload.uploader.on( 'all', function( type ) {
	            var stats;
	            switch( type ) {
	                case 'uploadFinished':
	                	upload.setState( 'confirm' );
	                    break;

	                case 'startUpload':
	                	upload.setState( 'uploading' );
	                    break;

	                case 'stopUpload':
	                	upload.setState( 'paused' );
	                    break;

	            }
	        });

	        upload.uploader.onError = function( code ) {
	            alert( 'Eroor: ' + code );
	        };
	        
	        upload.uploadBtn.on('click', function() {
	            if ( $(this).hasClass( 'disabled' ) ) {
	                return false;
	            }

	            if ( upload.state === 'ready' ) {
	            	upload.uploader.upload();
	            } else if ( upload.state === 'paused' ) {
	            	upload.uploader.upload();
	            } else if ( upload.state === 'uploading' ) {
	            	upload.uploader.stop();
	            }
	        });

	        upload.info.on( 'click', '.retry', function() {
	        	upload.uploader.retry();
	        } );

	        upload.info.on( 'click', '.ignore', function() {
	            alert( 'todo' );
	        } );

	        upload.uploadBtn.addClass( 'state-' + upload.state );
	        upload.updateTotalProgress();
	        
			return upload;  
    	}
    	
    	upload('.uploader_logo','.filePicker_logo','.filePicker2_logo','.dndArea_logo','#logo_id');
    	upload('.uploader_cover','.filePicker_cover','.filePicker2_cover','.dndArea_cover','#cover_id');

})( jQuery );
</script>
</block>